package commands

import (
	"errors"
	"strconv"

	"github.com/urfave/cli"

	"../flags"
	"../utils"
)

// Workplace - checkout workplace
func Workplace(config utils.Config) cli.Command {
	return cli.Command{
		Name: "workplace",
		Aliases: []string{
			"wp",
		},
		Usage:    "checkout workplace",
		Category: "DEVELOP COMMANDS",
		Flags: []cli.Flag{
			flags.Flags["path"],
			cli.StringFlag{
				Name:  "id",
				Usage: "task-`ID`",
			},
		},
		Action: makeAction(config, workplaceAction),
	}
}

func workplaceAction(conf utils.Config, git utils.Git, context *cli.Context) error {
	result, err := utils.LoadConfig(conf, git, "log")
	if err != nil {
		return err
	}

	ID := context.Int("id")
	TAG := "task-" + strconv.Itoa(ID)

	var active bool
	active, err = result.Bool(TAG, "active")
	if err != nil {
		return err
	}
	if !active {
		return errors.New("The workplace has inactive")
	}

	var branch string
	branch, err = result.String(TAG, "branch")
	if err != nil {
		return err
	}

	_, err = git.Execute(
		[]string{"checkout", branch},
	)
	return err
}
